<!-- description: index -->
<!-- fileName: index.vue -->
<!-- author: iwen(1044803551@qq.com) -->

<template>
  <div class="chat-container">
    <!-- 左侧边栏 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <button class="new-chat-btn" @click="createNewChat">
          <i class="icon">+</i> 新对话
        </button>
      </div>
      <div class="chat-list">
        <div 
          v-for="(chat, index) in chatList" 
          :key="index" 
          class="chat-item"
          :class="{ active: currentChatId === chat.id }"
          @click="switchChat(chat.id)"
        >
          <div class="chat-title">{{ chat.title }}</div>
          <div class="chat-time">{{ formatTime(chat.lastMessageTime) }}</div>
        </div>
      </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-main">
      <div class="chat-header">
        <div class="chat-title">{{ getCurrentChatTitle() }}</div>
      </div>

      <!-- 聊天消息区域 -->
      <div class="chat-messages" ref="messagesContainer">
        <div v-if="currentChatMessages.length === 0" class="empty-chat">
          <div class="welcome-message">开始新对话</div>
        </div>

        <div v-for="(message, index) in currentChatMessages" :key="index" class="message" :class="message.role">
          <div class="message-avatar">
            <div v-if="message.role === 'user'" class="user-avatar">U</div>
            <div v-else class="assistant-avatar">A</div>
          </div>

          <div class="message-content">
            <div v-if="message.role === 'assistant' && message.isThinking" class="thinking-container">
              <div class="thinking-header">
                <i class="thinking-icon">⚡</i>
                <span>思考中...</span>
              </div>
              <div class="thinking-content" v-if="message.thinkingContent">
                {{ message.thinkingContent }}
              </div>
            </div>

            <div class="message-text" v-html="message.content"></div>
          </div>
        </div>

        <!-- 输入状态指示器 -->
        <div v-if="isTyping" class="message assistant">
          <div class="message-avatar">
            <div class="assistant-avatar">A</div>
          </div>
          <div class="message-content">
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="chat-input-container">
        <div class="chat-input">
          <textarea 
            v-model="inputMessage" 
            placeholder="输入消息..." 
            @keydown.enter.prevent="sendMessage"
            rows="1"
            ref="messageInput"
          ></textarea>
          <button class="send-button" @click="sendMessage" :disabled="!inputMessage.trim() || isTyping">
            <i class="send-icon">→</i>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, onMounted } from 'vue';

// 聊天相关数据
const chatList = ref([
  { id: 1, title: '关于人工智能的讨论', lastMessageTime: new Date(2023, 10, 15, 14, 30) },
  { id: 2, title: 'Vue 3 开发技巧', lastMessageTime: new Date(2023, 10, 14, 10, 20) },
  { id: 3, title: '如何优化前端性能', lastMessageTime: new Date(2023, 10, 13, 9, 15) }
]);

const messages = ref({
  1: [
    { role: 'user', content: '什么是人工智能？' },
    { role: 'assistant', content: '人工智能（AI）是计算机科学的一个分支，致力于创建能够执行通常需要人类智能的任务的系统。' }
  ],
  2: [
    { role: 'user', content: 'Vue 3有哪些新特性？' },
    { role: 'assistant', content: 'Vue 3引入了许多新特性，包括Composition API、更好的TypeScript支持、性能提升等。' }
  ],
  3: []
});

const currentChatId = ref(1);
const inputMessage = ref('');
const isTyping = ref(false);
const messagesContainer = ref(null);
const messageInput = ref(null);

// 计算属性
const currentChatMessages = computed(() => {
  return messages.value[currentChatId.value] || [];
});

// 方法
const createNewChat = () => {
  const newChatId = Math.max(...chatList.value.map(chat => chat.id)) + 1;
  chatList.value.unshift({
    id: newChatId,
    title: '新对话',
    lastMessageTime: new Date()
  });
  messages.value[newChatId] = [];
  currentChatId.value = newChatId;
};

const switchChat = (chatId) => {
  currentChatId.value = chatId;
};

const getCurrentChatTitle = () => {
  const chat = chatList.value.find(c => c.id === currentChatId.value);
  return chat ? chat.title : '';
};

const formatTime = (date) => {
  const now = new Date();
  const diff = now - date;
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));

  if (days === 0) {
    return `${date.getHours()}:${date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()}`;
  } else if (days === 1) {
    return '昨天';
  } else if (days < 7) {
    return `${days}天前`;
  } else {
    return `${date.getMonth() + 1}/${date.getDate()}`;
  }
};

const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  });
};

const simulateThinking = (chatId) => {
  const thinkingMessage = {
    role: 'assistant',
    content: '',
    isThinking: true,
    thinkingContent: '我正在思考如何回答这个问题。让我分析一下用户的需求，然后组织一个合适的回答...'
  };

  messages.value[chatId].push(thinkingMessage);
  scrollToBottom();

  // 模拟思考时间
  return new Promise(resolve => {
    setTimeout(() => {
      // 移除思考消息
      const index = messages.value[chatId].findIndex(msg => msg.isThinking);
      if (index !== -1) {
        messages.value[chatId].splice(index, 1);
      }
      resolve();
    }, 2000);
  });
};

const simulateTypingEffect = (chatId, fullText) => {
  return new Promise(resolve => {
    const assistantMessage = {
      role: 'assistant',
      content: ''
    };

    messages.value[chatId].push(assistantMessage);
    const messageIndex = messages.value[chatId].length - 1;

    let currentIndex = 0;
    const typingInterval = setInterval(() => {
      if (currentIndex < fullText.length) {
        messages.value[chatId][messageIndex].content += fullText[currentIndex];
        currentIndex++;
        scrollToBottom();
      } else {
        clearInterval(typingInterval);
        resolve();
      }
    }, 20); // 控制打字速度
  });
};

const generateResponse = (userMessage) => {
  // 简单的模拟响应逻辑
  if (userMessage.includes('你好') || userMessage.includes('hi')) {
    return '你好！很高兴为您服务。请问有什么可以帮助您的吗？';
  } else if (userMessage.includes('天气')) {
    return '很抱歉，我无法获取实时天气信息。建议您查看天气预报应用程序或网站获取最新的天气情况。';
  } else if (userMessage.includes('时间')) {
    return `现在是 ${new Date().toLocaleString()}`;
  } else {
    return '感谢您的提问。这是一个很好的问题，让我为您详细解答。首先，我们需要理解这个问题的核心要点。其次，我们可以从不同角度来分析这个问题。最后，根据分析结果，我们可以得出一个全面的结论。希望这个回答对您有帮助！如果您还有其他问题，请随时提出。';
  }
};

const sendMessage = async () => {
  if (!inputMessage.value.trim() || isTyping.value) return;

  const userMessage = inputMessage.value.trim();
  inputMessage.value = '';

  // 添加用户消息
  messages.value[currentChatId.value].push({
    role: 'user',
    content: userMessage
  });

  // 更新聊天列表中的标题和时间
  if (messages.value[currentChatId.value].length === 1) {
    // 如果是第一条消息，使用消息作为标题
    const chatIndex = chatList.value.findIndex(chat => chat.id === currentChatId.value);
    if (chatIndex !== -1) {
      chatList.value[chatIndex].title = userMessage.length > 15 ? 
        userMessage.substring(0, 15) + '...' : userMessage;
    }
  }

  const chatIndex = chatList.value.findIndex(chat => chat.id === currentChatId.value);
  if (chatIndex !== -1) {
    chatList.value[chatIndex].lastMessageTime = new Date();
  }

  scrollToBottom();

  // 设置输入状态
  isTyping.value = true;

  try {
    // 模拟思考过程
    await simulateThinking(currentChatId.value);

    // 生成回复
    const response = generateResponse(userMessage);

    // 模拟打字效果
    await simulateTypingEffect(currentChatId.value, response);

    // 更新聊天列表中的时间
    if (chatIndex !== -1) {
      chatList.value[chatIndex].lastMessageTime = new Date();
    }
  } catch (error) {
    console.error('生成回复时出错:', error);
  } finally {
    isTyping.value = false;
    messageInput.value.focus();
  }
};

// 自动调整输入框高度
const adjustTextareaHeight = () => {
  nextTick(() => {
    if (messageInput.value) {
      messageInput.value.style.height = 'auto';
      messageInput.value.style.height = messageInput.value.scrollHeight + 'px';
    }
  });
};

// 监听输入变化
const handleInput = () => {
  adjustTextareaHeight();
};

// 挂载时初始化
onMounted(() => {
  messageInput.value.addEventListener('input', handleInput);
});
</script>

<style lang='scss' scoped>
.chat-container {
  display: flex;
  height: 100vh;
  background-color: #f7f7f8;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.sidebar {
  width: 260px;
  background-color: #171717;
  display: flex;
  flex-direction: column;
  color: #ececf1;

  .sidebar-header {
    padding: 15px;
    border-bottom: 1px solid #2d2d30;

    .new-chat-btn {
      width: 100%;
      padding: 12px;
      background-color: transparent;
      color: #ececf1;
      border: 1px solid #4d4d4f;
      border-radius: 6px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 14px;
      transition: background-color 0.2s;

      &:hover {
        background-color: #2d2d30;
      }

      .icon {
        margin-right: 8px;
        font-size: 18px;
      }
    }
  }

  .chat-list {
    flex: 1;
    overflow-y: auto;

    .chat-item {
      padding: 12px 15px;
      cursor: pointer;
      transition: background-color 0.2s;

      &:hover {
        background-color: #2d2d30;
      }

      &.active {
        background-color: #343541;
      }

      .chat-title {
        font-size: 14px;
        margin-bottom: 4px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .chat-time {
        font-size: 12px;
        color: #8e8ea0;
      }
    }
  }
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #ffffff;

  .chat-header {
    padding: 15px 20px;
    border-bottom: 1px solid #e5e5e5;

    .chat-title {
      font-size: 18px;
      font-weight: 500;
    }
  }

  .chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 20px;

    .empty-chat {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100%;

      .welcome-message {
        font-size: 20px;
        color: #8e8ea0;
      }
    }

    .message {
      display: flex;
      margin-bottom: 20px;

      &.user {
        flex-direction: row-reverse;

        .message-content {
          background-color: #f7f7f8;
          margin-right: 12px;
          margin-left: 0;
          border-radius: 18px 18px 4px 18px;
        }

        .message-avatar {
          margin-left: 12px;
          margin-right: 0;
        }
      }

      .message-avatar {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        font-weight: 600;
        color: white;
        margin-right: 12px;
        flex-shrink: 0;

        .user-avatar {
          background-color: #5436da;
        }

        .assistant-avatar {
          background-color: #10a37f;
        }
      }

      .message-content {
        max-width: 70%;
        background-color: #f7f7f8;
        border-radius: 18px 18px 18px 4px;
        padding: 12px 16px;

        .thinking-container {
          margin-bottom: 10px;
          padding: 10px;
          background-color: rgba(16, 163, 127, 0.1);
          border-radius: 8px;

          .thinking-header {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
            font-weight: 500;
            color: #10a37f;

            .thinking-icon {
              margin-right: 8px;
            }
          }

          .thinking-content {
            font-size: 14px;
            color: #666;
            line-height: 1.4;
          }
        }

        .message-text {
          line-height: 1.5;
          white-space: pre-wrap;
          word-wrap: break-word;
        }
      }
    }

    .typing-indicator {
      display: flex;
      align-items: center;
      height: 20px;

      span {
        height: 8px;
        width: 8px;
        background-color: #8e8ea0;
        border-radius: 50%;
        display: inline-block;
        margin: 0 2px;
        animation: typing 1.4s infinite;

        &:nth-child(2) {
          animation-delay: 0.2s;
        }

        &:nth-child(3) {
          animation-delay: 0.4s;
        }
      }
    }
  }

  .chat-input-container {
    padding: 15px 20px;
    border-top: 1px solid #e5e5e5;

    .chat-input {
      display: flex;
      align-items: flex-end;
      background-color: #f7f7f8;
      border-radius: 20px;
      padding: 10px 15px;

      textarea {
        flex: 1;
        border: none;
        outline: none;
        background-color: transparent;
        resize: none;
        font-size: 15px;
        line-height: 1.4;
        max-height: 200px;
        padding: 5px;
        font-family: inherit;
      }

      .send-button {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background-color: #10a37f;
        border: none;
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: background-color 0.2s;

        &:hover {
          background-color: #0d8f6e;
        }

        &:disabled {
          background-color: #e5e5e5;
          cursor: not-allowed;
        }

        .send-icon {
          font-size: 16px;
        }
      }
    }
  }
}

@keyframes typing {
  0% {
    transform: translateY(0);
    opacity: 0.7;
  }
  50% {
    transform: translateY(-5px);
    opacity: 1;
  }
  100% {
    transform: translateY(0);
    opacity: 0.7;
  }
}
</style>
